<?php
/**
 * Created by PhpStorm.
 * User: wenjoying@126.com
 * Date: 2018/5/31
 * Time: 10:16
 */

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Route;

class WeixinBaseController extends Controller
{
    const USER_IS_LOGIN = "USER_IS_LOGIN";//是否登录
    const USER_DATA     = "USER_DATA";//用户信息
    const USER_ID       = 'USER_ID';//用户ID

    /**
     * 设置不需要登录的的Action
     * @return array
     */
    protected function noLogin()
    {
        return [];
    }

    /**
     * 设置不需要验证的的Action
     * @return array
     */
    protected function noAuth()
    {
        return [];
    }

    /**
     * 获取当前的action,[controller,method]
     * @return array
     */
    protected function getCurrentAction()
    {
        $action = Route::current()->getActionName();
        list($class, $method) = explode('@', $action);
        $class = substr(strrchr($class, '\\'), 1);
        $class = str_replace("Controller", "", $class);
        return ['controller' => $class, 'method' => $method];
    }

    /**
     * Execute an action on the controller.
     * @param  string $method
     * @param  array  $parameters
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function callAction($method, $parameters)
    {
        if ($this->auth() !== true) {
            return $this->ajaxReturn(1004);
        }

        return parent::callAction($method, $parameters);
    }

    /**
     * 登录验证
     * */
    protected function auth()
    {
        $action   = $this->getCurrentAction();
        $actionID = $action['method'];
        $noLogin = $this->noLogin();

        if (in_array($actionID, $noLogin)) {//不需要登录，直接验证通过
            return true;
        } else {
            return self::checkLogin();
        }
    }

    /**
     * 判断当前用户是否登录
     */
    public static function checkLogin()
    {
        if (empty(session(self::USER_IS_LOGIN)) || empty(session(self::USER_DATA)) || empty(session(self::USER_ID))) {
            return false;
        }

        return true;
    }


}
